package com.clusterswisdom.horn.api.tmall.action.alipay.free;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.clusterswisdom.horn.api.db.DbUtil;

public class FreeUtil {
	
	public static String QUERY_SQL = "select * from t_freeType where freeType = ?";
	
	public static String INSERT_SQL = "insert into t_freeType (`freeType`) values (?)";
	
	public static DecimalFormat fromat = new DecimalFormat("000");
	
	public static String[] getFreeInfos(String commont) throws SQLException {
		if (commont == null) {
			return null;
		}
		
		String tradeId = getTradId(commont);
		String title = getTitle(commont, tradeId);
		
		return new String[]{tradeId, title, getFreeType(title)};
	}
	
	private static String getTitle(String commont, String tradeId) {
		if (commont == null) {
			return null;
		}
		
		if (tradeId != null) {
			commont = commont.replaceAll(tradeId, "");
		}
		
		int index = commont.indexOf(";");
		if (index > -1) {
			commont = commont.substring(0, index);
		}
		
		index = commont.indexOf("{");
		int eindex = commont.indexOf("}");
		if (index > -1 && eindex > -1) {
			commont = commont.substring(0, index);
		}
		
		index = commont.indexOf("[");
		eindex = commont.indexOf("]");
		if (index > -1 && eindex > -1) {
			commont = commont.substring(0, index);
		}
		
		return commont;
	}
	
	public static String getTradId(String commont) {
		Pattern pattern = Pattern.compile("[0-9]{7,}");
		Matcher matcher = pattern.matcher(commont);
		
		String tradeId = null;
		while (matcher.find()) {
			tradeId = matcher.group();
		}
		
		return tradeId;
	}
	
	private static String getFreeType(String title) throws SQLException {
		Connection conn = DbUtil.getUtil().getConnection();
		PreparedStatement statement = conn.prepareStatement(QUERY_SQL);
		statement.setString(1, title);
		
		ResultSet resultSet = statement.executeQuery();
		int id = -1;
		if (resultSet.next()) {
			id = resultSet.getInt(1);
		}
		resultSet.close();
		statement.close();
		
		if (id == -1) {
			statement = conn.prepareStatement(INSERT_SQL);
			statement.setString(1, title);
			statement.executeUpdate();
			statement.close();
			
			statement = conn.prepareStatement("select last_insert_id()");
			resultSet = statement.executeQuery();
			if (resultSet.next()) {
				id = resultSet.getInt(1);
			}
			
			resultSet.close();
			statement.close();
			conn.commit();
		}
		
		return fromat.format(id);
	}
}